import { loadMicroApp, initGlobalState, MicroAppStateActions } from 'qiankun';
import React from 'react';

class MicroAppB extends React.Component {
  constructor(props) {
    super(props);
  }

  microAppRef = null;

  // 页面渲染完成时，将应用手动挂载到#container
  componentDidMount() {
    console.log('MicroAppB componentDidMount');
    const { name, entry } = this.props;
    this.microAppRef = loadMicroApp({
      name,
      entry,
      container: '#containerB',
      props: { name: 'devui' },
    });
    console.log(this.microAppRef);
  }

  // 组件卸载是，将应用卸载
  componentWillUnmount() {
    const state = {
      microAppLoading: true,
    };

    // Initialize state 卸载子应用的时候，恢复原来的状态
    const actions: MicroAppStateActions = initGlobalState(state);
    actions.onGlobalStateChange((state, prev) => {
      // state: new state; prev old state
      console.log(state, prev);
    });
    actions.setGlobalState(state);
    actions.offGlobalStateChange();

    this.microAppRef.mountPromise.then(() => this.microAppRef.unmount());
  }

  render() {
    console.log('MicroAppB render containerB');
    return <div id="containerB" />;
  }
}

export default MicroAppB;
